<?php

namespace app\admin\model;

use think\Model;
use think\Request;

class Media extends Model
{

    

    

    // 表名
    protected $name = 'media';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        // 'playtime_text',
        // 'status_text'
        'image',
        'mv'
    ];
    

    
    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1')];
    }


    public function getPlaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['playtime']) ? $data['playtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setPlaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function getImageAttr($value,$data)
    {
        $value = $value ? $value : $data['image'];
        $domain = Request()->domain();
        return cdnurl($value,$domain);
    }
    public function getMvAttr($value,$data)
    {
        $value = $value ? $value : $data['mv'];
        $domain = Request()->domain();
        return cdnurl($value,$domain);
    }
    public static function list($para,$uid)
    {
        $page = $para['page'] ?? 1;
        $limit = $para['limit'] ?? 10;
        $where['status'] = 1;
        $log = MediaLog::field('times,media_id')
                        // ->group('media_id')
                        ->where('user_id',$uid)
                        ->buildSql();
        $list = self::alias('m')
                    ->field("id,times,title,image,mv,playtime")
                    ->join([$log => 'log'], 'm.id = log.media_id','left')
                    ->where($where)
                    ->order('times asc,id desc')
                    ->paginate()->toArray();
        foreach ($list['data'] as &$row) {
            if (!$row['times'])
                $row['times'] = 0; 
        }
        return $list;
    }
}
